define (require)->

    PostItemView = require "post/view/PostItemView"
    Collection = require "post/collection/PostCollection"

    Backbone.View.extend

        events: {
            "scroll": "_scroll"
        }

        initialize: (options)->
            @newCollection = options.newCollection
            @collection.on("reset", @_reset, @)
            @collection.on("add", @_appendItem, @)
            @newCollection.on("add", @_appendNewItem, @)


        _scroll: (e)->
            if (@$el.scrollTop() + @$el.height() == @$el.prop("scrollHeight"))
                @collection.nextPage()


        _reset: ()->
            self = @
            @collection.forEach((model)->
                self._appendItem(model)
            )


        _appendNewItem: (model)->
            self = @
            item = new PostItemView {
                model: model
            }
            @$el.prepend item.render().$el
            #            item.$el.fadeIn()
            item.on("delete", ->
                self.newCollection.remove(item.model)
                item.remove()
            )

        _appendItem: (model)->
            self = @
            item = new PostItemView {
                    model: model
            }
            @$el.append item.render().$el
#            item.$el.fadeIn()
            item.on("delete", ->
                self.collection.remove(item.model)
                item.remove()
            )

        render: ()->
            @collection.fetch()
            @
